/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package mail;

import portal.dao.CFG;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

/**
 *
 * @author Tadeu Augusto
 */
public class Mensageiro {

    public void enviar(String remetente, String assunto, String mensagem) {
        try {
            Properties props = new Properties();
            props.put("mail.smtp.host", "smtp.gmail.com");
            props.put("mail.smtp.port", "465");
            props.put("mail.smtp.socketFactory.port", "465");
            props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            props.put("mail.smtp.auth", "true");

            Session session = Session.getDefaultInstance(props, getAutenticador());
            
            session.setDebug(true);
            // Criar mensagem
            Message msg = new MimeMessage(session);
            
            //Definir remetente
            msg.setFrom(new InternetAddress(remetente));
            
            //Definir destinatário
            msg.setRecipient(Message.RecipientType.TO, new InternetAddress(CFG.destinatario));
            
            //Definir assunto e content type
            msg.setSubject(assunto);
            msg.setContent(mensagem, "text/html; charset=utf-8");
            
            Transport tr;
            try {
                tr = session.getTransport("smtp");
                tr.connect(props.getProperty("mail.smtp.host"), CFG.usuarioGmail, CFG.senhaGmail);
                msg.saveChanges();
                tr.sendMessage(msg, msg.getAllRecipients());
                tr.close();
            } catch(Exception e) {
                Logger.getLogger(Mensageiro.class.getName()).log(Level.SEVERE, null, e);
            }
        } catch (MessagingException ex) {
            System.out.println(ex);
        }
    }

    private Authenticator getAutenticador() {
        return new javax.mail.Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(CFG.usuarioGmail, CFG.senhaGmail);
            }
        };
    }
}
